package com.homer.commons.sscpprotocol.client.impl;

import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;

import com.homer.commons.sscpprotocol.client.DataSource;
import com.homer.commons.sscpprotocol.client.SocketOptions;

public class DataSourceImpl
  implements DataSource
{
  private String host;
  private int port = 8800;

  private boolean bigEndian = true;

  private Charset charset = Charset.defaultCharset();

  private SocketOptionsImpl socketOptions = new SocketOptionsImpl();

  public DataSourceImpl() {
  }

  public DataSourceImpl(String host, int port) {
    setHost(host);
    setPort(port);
  }

  public DataSourceImpl(String host, int port, boolean bigEndian) {
    setHost(host);
    setPort(port);
    setBigEndian(bigEndian);
  }

  public void setEncoding(String encoding) {
    this.charset = Charset.forName(encoding);
  }

  public String getEncoding() {
    return this.charset.name();
  }

  public void setBigEndian(boolean bigEndian) {
    this.bigEndian = bigEndian;
  }

  public boolean isBigEndian() {
    return this.bigEndian;
  }

  public String getHost() {
    return this.host;
  }

  public void setHost(String host) {
    this.host = host;
  }

  public int getPort() {
    return this.port;
  }

  public void setPort(int port) {
    this.port = port;
  }

  public SocketOptions getSocketOptions() {
    return this.socketOptions;
  }

  public Connection getConnection() throws IOException {
    return setModifies(new ConnectionImpl(this.host, this.port));
  }

  public Connection getConnection(String host) throws IOException {
    return setModifies(new ConnectionImpl(host, this.port));
  }

  public Connection getConnection(String host, int port) throws IOException {
    return setModifies(new ConnectionImpl(host, port));
  }

  protected Connection setModifies(ConnectionImpl conn) throws IOException {
    conn.setBigEndian(isBigEndian());
    conn.setEncoding(getEncoding());
    Socket socket = conn.socket();
    this.socketOptions.apply(socket);
    return conn;
  }
}
